let timer = null;
let timer2 = null;

let refund = new Vue({
    el: '.refund',
    data: {
        imgURL: visitimgurl,
        totalPage: 0,
        currentPage: 1,
        currentState: 0,
        tabLoading: false,
        applyTime: [],
        refundFormdata: { id: '', orderid: '', express_num: '',commodityState:'' },
        applyStates: [{ value: 0, label: '全部' }, { value: 1, label: '申请退款' }, { value: 2, label: '商家拒绝' }, { value: 3, label: '商家待退货' }, { value: 4, label: '商家待收货' }, { value: 5, label: '商家拒收货' }, { value: 6, label: '等待退款(已收到货)' }, { value: 8, label: '退款成功' }, { value: 9, label: '已取消' },],
        refundList: []
    },
    created() {
        this.getRefundProData()
    },
    methods: {
        handleCurrentChange(currentPage) {
            this.getRefundProData(currentPage)
        },
        handleSizeChange(size) {
            this.getRefundProData(size)
        },
        handleSearch() {
            console.log(this.refundFormdata);
            if (this.applyTime && this.applyTime.length > 0) {
                this.refundFormdata.startCreateTime = this.applyTime[0]
                this.refundFormdata.endCreateTime = this.applyTime[1]
            } else {
                delete this.refundFormdata.startCreateTime
                delete this.refundFormdata.endCreateTime
            }
            console.log(this.refundFormdata);
            this.getRefundProData()
        },
        handleStateItem(value) {
            this.refundFormdata.commodityState = value
            this.currentState = value
            this.getRefundProData()
        },
        changeState(v) {
            let obj = {}
            obj.commodityState = v.commodityState
            obj.id = v.id
            this.updataState(obj)
            console.log(v);
        },
        handleCheck(v) {
            SelectInfo(v.id)
            console.log('点击查询');
        },
        handleConfirmReceive(v) {
            let obj = {}
            obj.commodityState = 6
            obj.id = v.id
            this.updataState(obj, true)
            console.log('点击确认收货');
        },
        handleConfirmRefund(v) {
            console.log('点击确认退款');
            CreatRefundInfo(v)
        },
        handleCheckEMS(v) {
            console.log('点击查看物流');
            if (v.express_num) {
                SelectExpressInfo(v.express_num)
            }else{
                this.$message('暂无物流信息')
            }
        },
        changeStateCheck(v){
            console.log(v);
            this.currentState = v
            console.log(this.currentState);
            this.getRefundProData()
        },
        getRefundProData(pageNo) {
            this.tabLoading = true
            axios({
                url: httpurl + '/queryRefundCommodityRecordList',
                headers:{
                    "Authorization": GetTokenInfo()
                },
                params: {
                    ...this.refundFormdata,
                    pageNo: pageNo || 1,
                    pageSize: 10
                }
            }).then(res => {
                console.log(res);
                if (res.data.rtnCode == 200) {
                    this.tabLoading = false
                    let list = res.data.data.list
                    this.refundList = list
                    this.refundList.forEach((item, index) => {
                        console.log('进入循环');
                        if (item.img) {
                            let img = item.img.split(',')
                            list[index].img = img
                            // Vue.set(list[index],'img',img)
                        }else{
                            // Vue.set(list[index],'img',[])
                        }
                    })
                    console.log('循环外');

                    this.refundList = list
                    console.log(this.refundList);
                    this.totalPage = res.data.data.total
                }

            }).catch(err => {
                console.log(err);
                this.tabLoading = false

            })
        },
        updataState(option, updata) {
            axios({
                url: httpurl + '/updateRefundCommodityRecord',
                method: 'post',
                headers:{
                    "Authorization": GetTokenInfo()
                },
                params: {
                    ...option
                }
            }).then(res => {
                console.log(res);
                if (res.data.rtnCode == 200) {
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    if (updata) {
                        timer2 = setTimeout(() => {
                            clearTimeout(timer2)
                            this.getRefundProData()
                        }, 1500)
                    }
                } else {
                    this.$message({
                        message: res.data.msg
                    });
                    this.getRefundProData()
                }
            })
        },
        handleOrderId(id){
            console.log(id);
            window.location.href = `../order/DetaileOrder.html?OrderId=${id}`
        }
    }
})

layui.config({
    version: '1510164124181'
}).use(['form', 'laypage', 'layer', 'element', 'laydate'], function () {
    form = layui.form;
    layer = layui.layer;
    laypage = layui.laypage;//分页
    element = layui.element; //元素操作

});

function CreatRefundInfo(obj) {
    console.log(obj);
    let state = obj.refundRecordState
    // if (state > 0) {
    //     top.layer.alert("该状态下的退款数据不能退款!!请确认后再试!!")
    //     return;
    // }
    let money = obj.refundMoney
    let id = obj.id
    layer.open({
        type: 1,
        area: ['500px', '400px'],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 90%;margin: 0 auto;">' +
            '            <label for="username" style="font-size: 20px;">确认后，<span class="text-danger">' + money + '元</span>将退入买家账户:</label>' +
            '            <br><br><br>' +
            '            <span class="text-danger">我的备注:<textarea class="resons" value=""/></span></span>' +

            '            <div class="flex flex-wrap flex-col-3">' +
            '<div class="form-group-col-2">' +
            '<div class="form-label"></div>' +
            '<div class="form-cont padding_top10 margin_left2b">' +
            `<input type="button" onclick="addClickUpdate(this)" data-info="${state}" data-id="${id}" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;` +
            '<input type="button" value="取消" onclick="CloseLayuiAlert();" class="btn btn-danger"/>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '        </form>'
    });
}
// 退款接口
function addClickUpdate(obj) {
    let objs = {}
    objs.reson = $(".resons").val();
    objs.id = $(obj).attr('data-id');
    objs.state = $(obj).attr('data-info');
    top.layer.confirm('确认已经和客户沟通核实退款情况,确认后,该笔金额将直接退款到客户微信,是否确认？', { icon: 3, title: '提示信息' }, function (index) {
        // var index = top.layer.msg('提交中，请稍候', { icon: 16, time: 1000, shade: 0.8 });
        $.ajax({
            type: "POST",
            url: httpurl + "/updateRefundRecordListPc",
            cache: false,
            data: JSON.stringify({
                ...objs
            }),
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            success: function (data) {
                layer.closeAll();
                if (data.rtnCode == 200) {
                    top.layer.msg("提交成功!!请等待到账！！");
                } else {
                    top.layer.msg(data.msg, { time: 3000, shade: 0.8 });
                }
                timer = setTimeout(() => {
                    clearTimeout(timer)
                    refund.getRefundProData()
                }, 2000)
            },
            error: function (res) {
                top.layer.msg('网络请求失败，请稍后再试');
            }
        });
    }, function () {

    });


}

function SelectInfo(id) {
    // let id = $(obj).attr("data-id");
    top.layer.msg('加载中，请稍候', { icon: 16, time: false, shade: 0.8 });
    $.ajax({
        url: httpurl + "/refundRecordSate",
        cache: false,
        data: {
            id
        },
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        success: function (data) {
            top.layer.closeAll();
            if (data.rtnCode == 500) {
                top.layer.msg(data.msg)
                return;
            }
            let DataList = JSON.parse(data.msg);
            let dataInfo = '<table class="table table-bordered text-center"><tbody>' +
                '<tr>' +
                '<td>微信订单号:' + DataList.outTradeNo + '</td>' +
                '<td>商户订单号:' + DataList.transactionId + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>订单金额:' + DataList.totalFee / 100 + '</td>' +
                '<td>申请退款金额:' + (DataList.refundRecords[0].refundFee) / 100 + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>商户退款单号:' + DataList.refundRecords[0].outRefundNo + '</td>' +
                '<td>订单总退款次数:' + DataList.refundCount + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>退款渠道:' + DataList.refundRecords[0].refundChannel + '</td>' +
                '<td>退款状态:' + DataList.refundRecords[0].refundStatus + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td>退款入账账户:' + DataList.refundRecords[0].refundRecvAccount + '</td>' +
                '<td>退款成功时间:' + DataList.refundRecords[0].refundSuccessTime + '</td>' +
                '</tr>' +
                '<tr>' +
                '<td colspan="2">' +
                '<div class="form-cont">' +
                '<input type="button"  onclick="CloseLayuiAlert();" value="确认"  class="btn btn-info"/>&nbsp;&nbsp;' +
                '<input type="button" onclick="CloseLayuiAlert();" value="取消" class="btn btn-danger"/>' +
                '</div>' +
                '</td>' +
                '</tr>' +
                '</tbody></table>';
            layer.open({
                type: 1,
                area: ['800px', '400px'],
                shadeClose: false, //点击遮罩关闭
                content: dataInfo
            });
        }
    });

}

function CloseLayuiAlert() {
    layer.closeAll();
}

function SelectExpressInfo(expNo) {
    $.ajax({
        url: httpurl + "/kdniaoTrack",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            expNo:expNo
        },
        success: function (data) {
            let status = data.showapi_res_body.status;
            let info = "";
            if (status > 1) {
                let dataInfo = data.showapi_res_body.data;

                if (dataInfo.length > 0) {
                    for (let i = 0; i < dataInfo.length; i++) {
                        info += '<li class="layui-timeline-item">' +
                            '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>' +
                            '<div class="layui-timeline-content layui-text">' +
                            '<h3 class="layui-timeline-title">' + dataInfo[i].time + '</h3>' +
                            ' <p>' + dataInfo[i].context + '</p>' +
                            '</div>' +
                            '</li>';
                    }
                } else {
                    info += data.showapi_res_body.msg;
                }

            } else {
                info = (status == -1 ? "待查询" : (status == 0 ? "查询异常" : (status == 1 ? "暂无记录" : "暂无记录")));
                //-1 待查询 0 查询异常 1 暂无记录 2 在途中 3 派送中 4 已签收 5 用户拒签 6 疑难件 7 无效单 8 超时单 9 签收失败 10 退回
            }
            layer.open({
                type: 1,
                area: ['600px', '500px'],
                shadeClose: false, //点击遮罩关闭
                content: '<ul class="layui-timeline" style="width: 50%;margin: 0 auto">' + info + '</ul>'
            });


        }
    });
}

function amplificationImg(obj) {
    let url = $(obj).attr("src");
    console.log(url);
    $("#displayImg").attr("src", url);
    var height = $("#displayImg").height();//拿的图片原来宽高，建议自定义宽高
    var width = $("#displayImg").width();
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        shadeClose: true,
        area: [width + 'px', height + 'px'], //宽高
        content: "<img src=" + url + " />"
    });
}